<?php

namespace Biz\service\advertisement\apiModule;

use Biz\model\advertisement\MCustomCard;
use Doraemon\model\AdmCarouselBanner;
use Doraemon\model\Position\PositionBaseInfo;
use Doraemon\pockets\IdSender\IdSender;
use Doraemon\service\Article;
use Doraemon\service\Blank;
use Doraemon\service\Guide;
use Doraemon\service\Ideabook;
use Doraemon\service\MockDynamics;
use Doraemon\service\Photos;
use Doraemon\service\statSign\Basic;
use Doraemon\service\TopicActivity;
use Doraemon\tools\BlockType;
use Doraemon\tools\HhzClient;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\LinkFormat;
use Doraemon\tools\StatSign;

class HomeRecommendCard extends CardWithPos
{

    const FORMAT_HIT = 'formatPosHit';

    public function extUserProfileFl(): array
    {
        return ['addtime'];
    }


    /**
     * 推荐线api格式化输出
     * @param $hits
     * @param $uid
     * @param $userProfileExt
     * @param $statSignExt
     * @return array
     */
    public function format($hits, $uid, $userProfileExt, $statSignExt)
    {
        $response = [];
        if ($hits) {
            foreach ($hits as $hit) {
                //公共信息赋值
                $index = intval($hit['pos']);
                $reason = $hit['reason'];
                $type = null;
                $reasonBool = !in_array($reason, [PositionBaseInfo::REASON_TYPE_BUSINESS, PositionBaseInfo::REASON_TYPE_KA, PositionBaseInfo::REASON_TYPE_SUPER]);
                $posBool = in_array($index, [5, 10]);
                if ($reasonBool && $posBool) {
                    //day0用户去掉资源位5、10内容
                    $addtime = $this->userProfile->addtime;
                    $day = \Doraemon\service\position\data\CheckUserProfile::getDays($addtime);
                    if ($day == 1) {
                        continue;
                    }
                }
                if (in_array($hit['ext_type'], [self::EXT_TYPE_MOCK, self::EXT_TYPE_KA])) {
                    if ($hit['ext_type'] == self::EXT_TYPE_MOCK) {
                        //真假动态
                        $mock = json_decode($hit['pic_id'], true);
                        $obj_id = $mock['obj_id'] ?? '';
                        $type = $mock['obj_type'] ?? null;
                        $adv_text = $mock['ad_word'] ?? '';
                        $video_text = $mock['video_text'] ?? '';
                        $video_url = $mock['video_url'] ?? '';
                        $posi = StatSign::SUGGEST_CONTENT;
                    } else {
                        //KA广告
                        $ka = json_decode($hit['pic_id'], true);
                        $obj_id = $ka['obj_id'] ?? '';
                        $type = $ka['obj_type'] ?? null;
                        $adv_text = '';
                        $video_text = '';
                        $video_url = '';
                        $posi = 'recommendPage';
                    }

                    if (!$obj_id) {
                        continue;
                    }
                    $type = isset($type) ? $type : IdSender::getType($obj_id);
                    $tempData = [];
                    switch ($type) {
                        case BlockType::TYPE_IDEABOOK:
                            $ideaBook = Ideabook::listIdeaBookInfo([$obj_id]);
                            if ($ideaBook && isset($ideaBook[$obj_id])) {
                                $tempData = [
                                    'folder' => isset($ideaBook[$obj_id]) ? $ideaBook[$obj_id] : []
                                ];
                            }
                            break;
                        case BlockType::TYPE_TOPIC_ACTIVITY:
                            $topic = TopicActivity::getTopicInfosForList([$obj_id]);
                            $tempData = isset($topic[$obj_id]) ? $topic[$obj_id] : [];
                            break;
                        case IdSender::TYPE_PHOTO:
                        case IdSender::TYPE_ANSWER:
                            $type = BlockType::TYPE_PHOTO;
                            $photo_list = \Doraemon\service\Format\Note\HandleNote::handleNote([$obj_id], \Doraemon\service\Format\Note\HandleNote::MASONRY_LAYOUTS, $uid);
                            if ($photo_list && isset($photo_list[$obj_id])) {
                                $tempData = $photo_list[$obj_id];
                            }
                            break;
                        case IdSender::TYPE_GUIDE:
                            $type = BlockType::TYPE_GUIDE;
                            $guide_list = Guide::getGuidesForDynamic([$obj_id], $uid);
                            if ($guide_list && isset($guide_list[$obj_id])) {
                                $tempData = [
                                    'guide' => $guide_list[$obj_id],
                                    'action_info' => ['type' => 11, 'addtime' => $guide_list[$obj_id]['guide_info']['addtime']],
                                ];
                            }
                            break;
                        case IdSender::TYPE_ARTICLE:
                            $type = BlockType::TYPE_ARTICLE;
                            $article_list = Article::getArticlesForDynamic([$obj_id], $uid);
                            if ($article_list && isset($article_list[$obj_id])) {
                                $tempData = [
                                    'article' => $article_list[$obj_id],
                                    'action_info' => ['type' => 11, 'addtime' => $article_list[$obj_id]['article_info']['addtime']],
                                ];
                            }
                            break;
                        case IdSender::TYPE_BLANK:
                            $type = BlockType::TYPE_BLANK;
                            $blank_list = Blank::getBlanksForDynamic([$obj_id], $uid);
                            if ($blank_list && isset($blank_list[$obj_id])) {
                                $tempData = [
                                    'blank' => $blank_list[$obj_id],
                                ];
                            }
                            break;
                        case IdSender::TYPE_MOCK_DYNAMIC:
                            $posi = StatSign::SUGGEST_MOCK;
                            $type = BlockType::TYPE_MOCK_DYNAMIC;
                            $mock_list = MockDynamics::getMockInfoForDynamic([$obj_id], $uid, HhzClient::getClientVersion());
                            if ($mock_list && isset($mock_list[$obj_id])) {
                                $tempData = [
                                    'mock' => $mock_list[$obj_id],
                                ];
                                if (!empty($mock_list[$obj_id]['mock_info']['video_info'])) {
                                    $tempData['video_btn'] = (object)$mock_list[$obj_id]['mock_info']['video_btn'];
                                }
                            }
                            break;
                        case IdSender::TYPE_WIKI_ALBUM:
                            $album_list = \Biz\service\Album\AlbumListService::getAlbumListByAlbumIds([$obj_id]);
                            $map = [];
                            foreach ($album_list as $info) {
                                if (isset($info['album_info'])) $map[$info['album_info']['album_id']] = $info;
                            }
                            if (isset($map[$obj_id])) {
                                $tempData = $map[$obj_id];
                            }
                            break;
                        default:
                            if ($type) {
                                $tempData = [
                                    'obj_type' => $type,
                                    'obj_id' => $obj_id,
                                ];
                            }
                            break;
                    }

                    if ($tempData) {
                        $tempData = [
                                'index' => $index,
                                'is_ad' => 1,
                                'adv_text' => $adv_text,
                                'type' => $type,
                                'obj_id' => $obj_id,
                            ] + $tempData + ['statSign' => $this->statSign($hit, [Basic::EXTEND_KEY_OBJ_ID => $obj_id])];
                    }
                } elseif ($hit['ext_type'] == CardWithPos::CARD_EXT_TYPE_TOPIC) {
                    if (!($hit['ext'] instanceof MCustomCard)) {
                        $hit['ext'] = new MCustomCard($hit['ext']);
                    }
                    $tempData = [
                        'index' => $index,
                        'statSign' => $this->statSign($hit),
                    ] + $this->formatTopicCard($hit['ext']);
                } elseif ($hit['ext_type'] == CardWithPos::CARD_EXT_TYPE_SIMILAR) {
                    if (!($hit['ext'] instanceof MCustomCard)) {
                        $hit['ext'] = new MCustomCard($hit['ext']);
                    }
                    $tempData = [
                            'index' => $index,
                            'statSign' => $this->statSign($hit),
                        ] + $this->formatSimilarCard($hit['ext']);
                } else {
                    $pic_ids = json_decode($hit['pic_id'], true);
                    $linkParams = $hit['link_params'];
                    $statSign = $this->statSign($hit, $statSignExt);
                    if ($linkParams && is_string($linkParams)) {
                        $linkParams = json_decode($linkParams, true);
                        $linkParams['statSign'] = urlencode(base64_encode($statSign));
                    }
                    $link = $this->generateLink($hit['link_type'], $linkParams);
                    $tempData = [
                        'type' => BlockType::TYPE_BANNER,
                        'banner' => [
                            'id' => $hit['id'],
                            'index' => $index,
                            'banner' => empty($pic_ids['single_pic_id']) ? '' : ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $pic_ids['single_pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI),
                            'double_banner' => empty($pic_ids['double_pic_id']) ? '' : ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $pic_ids['double_pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI),
                            'link' => $link,
                            'statType' => (string)'banner' . BlockType::TYPE_CAROUSEL_BANNER . '-' . AdmCarouselBanner::SHOW_TYPE_RECOMMEND,
                        ],
                        'statSign' => $statSign,
                        'index' => $index,
                    ];
                }

                if ($tempData) {
                    $response[] = $tempData;
                }
            }
        }

        //按index排序
        if ($response) {
            $sort = array_column($response, 'index');
            array_multisort($sort, SORT_ASC, $response);
        }

        return $response;
    }

    public function formatAdmListExtInfo(&$v, $map)
    {
        $pic_ids = json_decode($v['pic_id'], true);
        $ext_type = $v['ext_type'];
        switch ($ext_type) {
            case self::EXT_TYPE_MOCK:
                $v['obj_type'] = $pic_ids['obj_type'] ?? '';
                $v['obj_id'] = $pic_ids['obj_id'] ?? '';
                $v['ad_word'] = $pic_ids['ad_word'] ?? '';
                break;
            case self::EXT_TYPE_KA:
                $v['obj_type'] = $pic_ids['obj_type'] ?? '';
                $v['obj_id'] = $pic_ids['obj_id'] ?? '';
                break;
            default:
                $v['single_pic_url'] = empty($pic_ids['single_pic_id']) ? '' : ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $pic_ids['single_pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI);
                $v['double_pic_url'] = empty($pic_ids['double_pic_id']) ? '' : ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $pic_ids['double_pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI);
                break;
        }
    }

    public function extListMap($ids)
    {
        return MCustomCard::getInfos($ids);
    }

    public function getExtInfo($baseInfo)
    {
        $ext_type = $baseInfo['ext_type'] ?? self::EXT_TYPE_FLOW;
        $link_type = $baseInfo['link_type'] ?? '';
        $link_params = $baseInfo['link_params'] ?? '';
        $pic_id = json_decode($baseInfo['pic_id'], true);
        $response = [
            'ext_type' => $ext_type
        ];
        switch ($ext_type) {
            case self::EXT_TYPE_FLOW:
                $response['single_pic_id'] = $pic_id['single_pic_id'] ?? '';
                $response['double_pic_id'] = $pic_id['double_pic_id'] ?? '';
                break;
            case self::EXT_TYPE_MOCK:
                $response['obj_id'] = $pic_id['obj_id'] ?? '';
                $response['obj'] = compact('link_type', 'link_params');
                $response['ad_word'] = $pic_id['ad_word'] ?? '';
                $response['video_text'] = $pic_id['video_text'] ?? '';
                $response['video_url'] = $pic_id['video_url'] ?? '';
                $response['video'] = [
                    'link_type' => $pic_id['link_type'] ?? '',
                    'link_params' => $pic_id['link_params'] ?? '',
                ];
                break;
            case self::EXT_TYPE_KA:
                $response['obj'] = compact('link_type', 'link_params');
                break;
            case CardWithPos::CARD_EXT_TYPE_TOPIC:
                $info = MCustomCard::getInfo($baseInfo['id']);
                $response['card_topic'] = [
                    'photo' => $info->photo,
                    'module_icon' => $info->module_icon,
                    'sub_title' => $info->sub_title,
                    'convert' => $info->convert,
                    'ranking_link' => [
                        'link_type' => $info->link_type,
                        'link_params' => $info->link_params,
                    ]
                ];
                break;
            case CardWithPos::CARD_EXT_TYPE_SIMILAR:
                $info = MCustomCard::getInfo($baseInfo['id']);
                $response['card_similar'] = [
                    'photo' => $info->photo,
                    'module_icon' => $info->module_icon,
                    'main_title' => $info->main_title,
                    'sub_title' => $info->sub_title,
                    'bottom_background_image' => $info->bottom_background_image,
                    'convert' => $info->convert,
                    'ranking_link' => [
                        'link_type' => $info->link_type,
                        'link_params' => $info->link_params,
                    ]
                ];
                break;
            default:
                break;
        }

        return $response;
    }

    public function uniquePos($v): string
    {
        return $v['pos'];
    }

}